package com.andon.springboot.seed.interceptor;

import com.alibaba.fastjson.JSON;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author: baiwenlong
 * created on: 2018/11/15 3:57 PM
 * description: http 拦截器  对请求的监听
 */
public class HttpInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(HttpInterceptor.class);
    public static final String START_TIME = "requestStartTime";

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        Map<String, String[]> parameterMap = request.getParameterMap();
        logger.info("request start url:{}, params:{}", url, JSON.toJSONString(parameterMap));
        request.setAttribute(START_TIME, System.currentTimeMillis());
        return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        String url = request.getRequestURI();
//        long startTime = (long) request.getAttribute(START_TIME);
//        long end = System.currentTimeMillis();
//        logger.info("request finish url:{}, cost:{}", url, end - startTime);
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行
     * （主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURI();
        long startTime = (long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        logger.info("request complete url:{}, cost:{}", url, end - startTime);
    }
}
